import hashlib
import sanicdb
from sanic import app
import jwt
import datetime

# 密码加盐值
pwd_salt = "cd4db5ed3bb972c57ad0847478d7e707"

# jwt 密钥
jwt_secret = "fewa@#$%^&fewajoioio%(*&$$HUIfew"
# jwt 签名
jwt_issuer = "OPpfewajio&%IO(@$ePFEIiddggwaaeg"
# 过期时间，秒
jwt_seconds = 60 * 60 * 2


# 显性取参
def get_params(params: dict, param: str, default: str, required: bool):
    if required:
        if not params.get(param):
            raise Exception(param + " is not fund")

    return params.get(param, default)


# 参数校验
def params_verify(requests):
    params = requests.json

    if not params:
        raise Exception("参数错误")

    if not params.get("act"):
        raise Exception("接口号错误")

    return params


# 密码加盐
def employee_password_md5(s: str):
    s = s + pwd_salt
    news = str(s).encode()
    m = hashlib.md5(news)
    return m.hexdigest()


# 加载系统参数
async def load_sys_params(request: app.Sanic, conn_id: sanicdb.SanicDB):
    is_load_key = "load_sys_params"
    # 系统参数只加载一次
    loading = await request.redis_pool.set(is_load_key, 1, ex=60, nx=True)
    if loading is None:
        return
    # 获取所有系统参数
    sql = "select * from sys_param where is_valid = '0' "

    result = await conn_id.query(sql)

    for sys_param in result:
        if sys_param["param_type"] == "salt" and sys_param["param_code"] == "pwd_salt":
            global pwd_salt
            pwd_salt = sys_param["param_val"]

        await request.redis_pool.hset(
            name="sys_params", key=sys_param["param_type"] + "&" + sys_param["param_code"],
            value=sys_param["param_val"])

    await request.redis_pool.delete(is_load_key)


# 生成jwt
def generate_jwt(data: dict):
    dic = {
        'exp': datetime.datetime.now() + datetime.timedelta(seconds=jwt_seconds),  # 过期时间
        'iat': datetime.datetime.now(),  # 开始时间
        'iss': jwt_issuer,  # 签名
        'data': data,
    }

    return jwt.encode(dic, jwt_secret, algorithm='HS256').decode()  # 加密生成字符串


# jwt 解码
def jwt_decode(jwt_str: str):
    # jwt 解密，校验签名
    data = jwt.decode(jwt_str, jwt_secret, issuer=jwt_issuer, algorithms=['HS256'])
    return data
